import { PostService } from '~/server/database/services/postService'
import LikeService from '~/server/database/services/likeService'

export default defineEventHandler(async (event) => {
  try {
    const id = parseInt(getRouterParam(event, 'id') || '0')
    
    if (!id || id <= 0) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '无效的帖子ID' }
      })
    }

    const post = await PostService.getPostById(id)
    
    if (!post) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Not Found',
        data: { message: '帖子不存在' }
      })
    }

    // 增加浏览次数
    await PostService.incrementViewCount(id)

    // 如果用户已登录，检查点赞状态
    let userId: number | null = null
    try {
      const { requireAuth } = await import('~/server/utils/auth')
      const user = await requireAuth(event)
      userId = user.id
    } catch {
      // 用户未登录，跳过点赞状态检查
    }

    // 添加点赞状态
    if (userId) {
      post.isLiked = await LikeService.isLiked(userId, 'post', post.id)
    }

    return {
      success: true,
      data: post
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    if (error.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      data: { message: '获取帖子详情失败' }
    })
  }
})
